﻿using System;
using System.Collections.Generic;
using System.Web.Routing;
using System.Text;
using System.Web.Mvc;

namespace ScoutNET.Helpers
{
    public static class CheckBoxListHelper
    {
        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo)
        {
            return CheckBoxList( htmlHelper ,name, listInfo,((IDictionary<string, object>) null));
        }

        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, object htmlAttributes)
        {
            return CheckBoxList(htmlHelper , name, listInfo, ((IDictionary<string, object>)new RouteValueDictionary(htmlAttributes)));
        }

        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, IDictionary<string, object> htmlAttributes)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException("The argument must have a value", "name");
            if (listInfo == null)
                throw new ArgumentNullException("listInfo");
            if (listInfo.Count < 1)
                throw new ArgumentException("The list must contain at least one value", "listInfo");

            StringBuilder sb = new StringBuilder();

            foreach (CheckBoxListInfo info in listInfo)
            {
                TagBuilder builder = new TagBuilder("input");
                if (info.IsChecked) builder.MergeAttribute("checked", "checked");

                    builder.MergeAttributes<string, object>(htmlAttributes);
                    builder.MergeAttribute("type", "checkbox");
                    builder.MergeAttribute("value", info.Value);
                    builder.MergeAttribute("name", name);
                    if (!string.IsNullOrEmpty(info.DisplayText))
                    {
                        builder.InnerHtml = info.DisplayText;
                    }

                    sb.Append(builder.ToString(TagRenderMode.Normal));
            }

            return MvcHtmlString.Create(sb.ToString());
       }
    }

  
    public class CheckBoxListInfo 
    {

       public CheckBoxListInfo(string value, string displayText, bool isChecked)
       {
           this.Value = value;
           this.DisplayText = displayText;
           this.IsChecked = isChecked;
       }

       public string Value { get; private set; }

       public string DisplayText { get; private set; }

       public bool IsChecked { get; private set; }

   }
}
